package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.inteceptor.CartInteceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author yanjingren
 * @Date 2021/6/28
 * @Description com.atguigu.gulimall.cart.service.impl
 */
@Service
@Slf4j
public class CartServiceImpl implements CartService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private final String CART_PREFIX = "gulimall:cart:";

    @Resource
    private ProductFeignService productFeignService;

    @Resource
    private ThreadPoolExecutor executor;

    /**
     * 添加商品到购物车
     * @param skuId 商品id
     * @param num 数量
     * @return
     */
    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisData = (String) cartOps.get(skuId.toString());
        if (StringUtils.isEmpty(redisData)) {
            CartItem cartItem = new CartItem();
            // 添加新商品到购物车
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                // 1.远程查询当前要添加的商品的信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo data = r.getData("skuInfo", new TypeReference<SkuInfoVo>(){});
                // 2.将商品添加到购物车
                cartItem.setCheck(true);
                cartItem.setCount(num);
                cartItem.setImage(data.getSkuDefaultImg());
                cartItem.setTitle(data.getSkuTitle());
                cartItem.setPrice(data.getPrice());
                cartItem.setSkuId(skuId);
            }, executor);

            // 3.远程查询sku的组合信息
            CompletableFuture<Void> getSkuAttrTask = CompletableFuture.runAsync(() -> {
                List<String> skuSaleAttrValue = productFeignService.getSkuSaleAttrValue(skuId);
                cartItem.setSkuAttr(skuSaleAttrValue);
            }, executor);

            // 4、两个异步任务都完成，才能把数据放到redis中
            CompletableFuture.allOf(getSkuInfoTask, getSkuAttrTask).get();

            String jsonString = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), jsonString);
            return cartItem;
        } else {
            // 购物车有此商品，修改数量即可
            CartItem cartItem = JSON.parseObject(redisData, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
            return cartItem;
        }
    }

    /**
     * 获取购物车中购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisData = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(redisData, CartItem.class);
    }

    /**
     * 获取整个购物车
     * @return
     */
    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
//        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        Cart cart = new Cart();
        // 1.区分登录还是不登录
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();
        if (userInfoTo.getUserId() != null) {
            // 登录状态
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String tempCartKey = CART_PREFIX + userInfoTo.getUserKey();
            // 如果临时购物车内还有数据，则进行合并
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (!CollectionUtils.isEmpty(tempCartItems)) {
                // 需要合并
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                // 合并完成，清楚临时购物车的数据
                clearCart(tempCartKey);
            }
            // 此时包含合并过来的临时数据和登录后的购物车数据
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            // 没登录
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(cartKey));
        }
        log.info("获取购物车完成：\n{}", cart.toString());
        return cart;
    }

    /**
     * 清空购物车的数据
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey) {
        stringRedisTemplate.delete(cartKey);
    }

    /**
     * 勾选购物项
     * @param skuId
     * @param check
     */
    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 更新商品数量
     * @param skuId
     * @param num
     */
    @Override
    public void countItem(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonString);
    }

    /**
     * 删除购物车中商品
     * @param skuId
     */
    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            List<CartItem> cartItems = getCartItems(CART_PREFIX + userInfoTo.getUserId());
            // 获取所有被选中的购物项
            List<CartItem> collect = cartItems.stream().filter(b -> b.getCheck()).map(item -> {
                // 更新为最新价格
                R r = productFeignService.getPrice(item.getSkuId());
                BigDecimal price = r.getData(new TypeReference<BigDecimal>() {});
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());
            return collect;
        }
    }

    /**
     * 获取到要操作的购物车
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        UserInfoTo userInfoTo = CartInteceptor.threadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        return hashOps;
    }

    /**
     * 获取购物车内指定key的所有购物项
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = stringRedisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (!CollectionUtils.isEmpty(values)) {
            return values.stream().map(b -> JSON.parseObject((String) b, CartItem.class)).collect(Collectors.toList());
        }
        return null;
    }

}
